import {Component, ViewEncapsulation, Input, ViewChild} from '@angular/core';
import {UserService} from '../../../../services/app.user';
import {BaThemeSpinner}  from '../../../../theme/services';
import {Utility} from '../../../../services/app.utility';
import {AuthenticationHelper} from '../../../../app.authentication';
import {Router} from '@angular/router';
import {LocalDataSource} from 'ng2-smart-table';
import {Constants} from '../../../../common/app.constants';
declare let toastr:any;
declare let $:any;

@Component({
    selector: 'UserLog',
    encapsulation: ViewEncapsulation.None,
    templateUrl: './userLog.html',
    styleUrls: ['./userLog.scss']
})


export class UserLog {

  public start:any;
  public end:any;
  public check:any;
    @Input()
      data = [];
    constants:Constants;
    query:string = '';
    skipItem: number = 0;
  removePagination: boolean = true;
  fromDate: string = '';
  toDate: string = '';
//@ViewChild('userLogTable') userLogTable: Ng2SmartTableComponent;
    settings = {
        add: {
            addButtonContent: '<i class="ion-ios-plus-outline"></i>',
            createButtonContent: '<i class="ion-checkmark"></i>',
            cancelButtonContent: '<i class="ion-close"></i>',
        },
        edit: {
            editButtonContent: '<i class="ion-edit"></i>',
            saveButtonContent: '<i class="ion-checkmark"></i>',
            cancelButtonContent: '<i class="ion-close"></i>',
        },
        delete: {
            deleteButtonContent: '<i class="ion-trash-a"></i>',
            confirmDelete: true
        },
        columns: {
            createdAt: {
                title: 'Timestamp',
                type: 'string'
            },
            name: {
               title: 'Name',
               type: 'string'
            },
            action: {
                title: 'Action',
                type: 'string'
            },
            target: {
                title: 'Target',
                type: 'string'
            },
            context: {
                title: 'Context',
                type: 'string'
            }
        }
    };

    source:LocalDataSource = new LocalDataSource();

    public userId:any;
    public userName:any;
    myDatePickerOptions: any = {};
    constructor(private userService:UserService, private spinner:BaThemeSpinner, public utility: Utility, private router:Router, private authentication:AuthenticationHelper) {
        this.constants = new Constants();
      let todayDate = new Date();
      this.myDatePickerOptions = {
        todayBtnTxt: 'Today',
        dateFormat: 'dd/mm/yyyy',
        firstDayOfWeek: 'mo',
        sunHighlight: true,
        inline: false,
        disableSince: {
          year: todayDate.getFullYear(),
          month: todayDate.getUTCMonth() + 1, day: todayDate.getDate() + 1
        },
        selectionTxtFontSize: '16px'
      };

      this.start = 0;
      this.check = 0;

      // start timer for timestamp
      this.startCount();
    }

    // Call for get user info after load view
    ngAfterViewInit() {
      this.fromDate = this.utility.getFormattedDateForTree(this.utility.getMonthsAgoDate(1));
      this.toDate = this.utility.getFormattedDateForTree(new Date());

      this.data = [];
      this.source.load(this.data);
        this.userService.getuserInfo().subscribe(
            data => this.userInfoSuccess(data),
            error => {}
        );
    }

    // Call for get user info successfully
    public userInfoSuccess(data) {
        console.log("user log");
        this.spinner.showProgress();
        if (this.utility.userDetailFlag) {
            this.logs();
            this.userName = this.utility.userDetails.name;
        } else {
            this.logs();
            this.userName = data.firstName;
        }
        this.utility.userDetailFlag = false;
    }

    // funtion for Get user log data using API call
    public logs() {
        let input = {
          "fromDate" : this.fromDate,
          "skipItem" : this.skipItem,
          "itemsperPage" : "10",
           "toDate" : this.toDate,
            "userId": ''
        };
      if(this.utility.userDetailFlag){
        input.userId = this.utility.userDetails._id;
      } else {
        delete input.userId;
      }
        this.userService.getuserLogData(input).subscribe(
            data => {
                this.getData(data);
            });
    }

    // Function for received log data and send to smart table
    public getData(data) {
      if(data.logCount<=this.skipItem){
        this.removePagination = false;
      }
      if (data.logList) {
        if(this.skipItem==0){
          this.data = [];
        }
        data.logList.forEach(item => {
          let data = {
            createdAt: this.utility.getFormattedDate(item.createdAt),
            target: item.target,
            action: item.action,
            name: item.name,
            context: item.context
          }
          this.data.push(data);
      //
        })
        this.spinner.hideProgress();
        this.source.load(this.data);
        this.source.reset();
        this.source.setPage(this.skipItem);
      }
    }
  getLogData(){
      this.skipItem += 10;
      this.logs();
  }
  // Search Data

  searchUserData($event){
      this.skipItem = 0;
      this.logs();
  }

    // Function for get CSV from server
    public getCSV(event) {
      let input = {
        "fromDate": this.utility.getFormattedDateForTree(this.utility.getMonthsAgoDate(1)),
        "toDate": this.utility.getFormattedDateForTree(new Date()),
        'userId': this.userId,
        'csvType': 'userLogs'
      };
      if(this.utility.userDetailFlag){
        input.userId = this.utility.userDetails._id;
      } else {
        delete input.userId;
      }
        this.userService.getLogAllCSV(input).subscribe(
          data => this.getCSVSuccess(data),
          error => {}
        );
    }

    // Function for download user log data CSV
    public getCSVSuccess(data) {
        let url = this.constants.LINK;
        let fileName = data.substr(1, data.length);
        let urlOfFile = url + '' + fileName;
        window.open(urlOfFile, '_blank');
    }

  onFromDateChanged(event:any) {
    if (event.formatted === '') {

    } else {
      let day, month;
      day = event.date.day;
      month = event.date.month;
      if (event.date.month < 10) {
        month = 0 + '' + event.date.month;
      }
      if (event.date.day < 10) {
        day = 0 + '' + event.date.day;
      }

      this.fromDate = day + '/' + month + '/' + event.date.year;
    }
  }
  // Fuction for change To date of datepicker
  onToDateChanged(event:any) {
      if (event.formatted === '') {

      } else {
        let day, month;
        day = event.date.day;
        month = event.date.month;
        if (event.date.month < 10) {
          month = 0 + '' + event.date.month;
        }
        if (event.date.day < 10) {
          day = 0 + '' + event.date.day;
        }

        this.toDate = day + '/' + month + '/' + event.date.year;
      }
    }

  // To call every 1 sec for count how much time we spent on this page
  public  timedCount() {
    this.start = this.start + 1;
    this.end = setTimeout(() => {
      this.timedCount()
    }, 1);
  }

  // To function for start timstamp count
  public startCount() {
    if (!this.check) {
      this.check = 1;
      this.timedCount();
    }
  }

  // To function for stop timstamp count
  public stopCount() {
    clearTimeout(this.end);
    this.check = 0;
  }

  ngOnDestroy() {
    // To stop count function call
    this.stopCount();

    // API call for tract navigation sequence
    let seq = {
      sequence: {
        "pageName": 'admin/userlog',
        "timeSpent": this.start
      }

    };
    this.userService.setUrlSeq(seq).subscribe();
  }
}
